import { Blog } from "../model/Blog.js";
import { Op } from 'sequelize'

const fn_list = async (ctx,next) => {
    let keyword = ctx.request.query.keyword || '' ;
    
    let where;
    if(keyword){
        where = {
            [Op.or] : [
                {
                    title:{
                        [Op.like] : `%${keyword}%`
                    },
                },{
                    author:{
                        [Op.like] : `%${keyword}%`
                    },
                }
            ]
        }
    }
    let blogs = await Blog.findAll(
        { where }
    );
    ctx.body = {
        code: 1000,
        msg: '列表成功',
        data: blogs
    }
}
const fn_getById = async (ctx,next) => {
    let id = ctx.params.id || 0;
    let blog = await Blog.findByPk(id);
    ctx.body={
        code:1000,
        msg:'成功',
        data: blog
    }
}
const fn_add = async (ctx,next) => {
    let obj = ctx.request.body;
    if (obj && obj.title && obj.author && obj.title.length > 0 && obj.title.length <50 && obj.author.length > 1 && obj.author.length <10) {
        let blog = await Blog.create(obj)
        ctx.body = {
            code : 1000,
            msg : '保存成功',
            data : blog
        }
    }else{
        ctx.body = {
            code : 3000,
            msg : '标题或作者不符合规范，保存失败',
        } 
    }
}
const fn_edit = async (ctx,next) => {
    let obj = ctx.request.body;
    let id = ctx.params.id || 0;
    await Blog.update(obj, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: '修改成功',
        data: null
    }
}
const fn_del = async (ctx,next) => {
    let id = ctx.params.id || 0;
    let count = await Blog.destroy({
        where :{
            id:id
        }
    })
    let res ;
    if(count === 1){
        res={
            code:1000,
            msg:"删除成功",
            data:null
        }
    } else {
        res={
            code:4000,
            msg:"删除失败",
            data:null
        }
    }
    ctx.body = res;
}

export default [
    {
        method:"get",
        url:"/blogs",
        fn:fn_list
    },
    {
        method:"get",
        url:"/blogs/:id",
        fn:fn_getById
    },
    {
        method:"post",
        url:"/blogs",
        fn:fn_add
    },
    {
        method:"put",
        url:"/blogs/:id",
        fn:fn_edit
    },
    {
        method:"del",
        url:"/blogs/:id",
        fn:fn_del
    }
]